# encoding: utf-8
class TopicsController < ApplicationController
  before_filter :authenticate_user!
  before_filter :get_project, :only => [:new, :edit, :create, :update]
  before_filter :is_member_of_project?
  before_filter :is_owner_of_topic?, :only => [:edit, :update]
  
  def index
    @topics = Topic.where(:project_id => params[:project_id]).order("updated_at desc")

    respond_to do |format|
      format.html
      format.xml  { render :xml => @topics }
    end
  end

  def show
    @topic = Topic.find(params[:id])

    respond_to do |format|
      format.html
      format.xml  { render :xml => @topic }
    end
  end

  def new
    @topic = Topic.new

    respond_to do |format|
      format.html
      format.xml  { render :xml => @topic }
    end
  end

  def edit
    @topic = Topic.find(params[:id])
  end

  def create
    @topic = Topic.new(params[:topic])
    @topic.project_id = params[:project_id]
    @topic.user_id = current_user.id

    respond_to do |format|
      if @topic.save
        flash[:notice] = t :topic_create_success, :scope => [:flash, :notice]
        format.html { redirect_to(project_topic_path(params[:project_id], @topic)) }
        format.xml  { render :xml => @topic, :status => :created, :location => @topic }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @topic.errors, :status => :unprocessable_entity }
      end
    end
  end

  def update
    @topic = Topic.find(params[:id])
    @bug = Bug.where(:topic_id => @topic.id).first

    ActiveRecord::Base.transaction do
      respond_to do |format|
        if @topic.update_attributes(params[:topic]) && @bug.update_attributes(:title => @topic.name, :description => @topic.description)
          flash[:notice] = t :topic_edit_success, :scope => [:flash, :notice]
          format.html { redirect_to(project_topic_path(params[:project_id], @topic)) }
          format.xml  { head :ok }
        else
          format.html { render :action => "edit" }
          format.xml  { render :xml => @topic.errors, :status => :unprocessable_entity }
        end
      end
    end
  end

  private
  def is_owner_of_topic?
    unless(Topic.find(params[:id]).user_id == current_user.id)
      flash[:error] = t :topic_no_right, :scope => [:flash, :error]
      redirect_to project_topic_path(params[:project_id], params[:id])
    end
  end
end
